import java.io.*;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Vector;
import java.awt.*;
import java.awt.event.*;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;
import javax.swing.filechooser.*;
import comirva.audio.util.MFCC;
import comirva.web.crawling.agmis.ExaleadRetriever;

public class Window extends JPanel
                             implements ActionListener {
    static private final String newline = "\n";
    JButton openButton, evalButton, saveButton, createModel;
    JTextArea log;
    JFileChooser fc;
    File[] file;
    MfccCreation mfcc=new MfccCreation();
    ArrayList<String> nomiFile;
    javax.swing.filechooser.FileFilter filter;

    public Window(){
        super(new BorderLayout());

        //Create the log first, because the action listeners
        //need to refer to it.
        log = new JTextArea(5,20);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(log);

        //Create a file chooser
        fc = new JFileChooser("C:\\Users\\Andrea\\Desktop");
        

        //Create the open button.  We use the image from the JLF
        //Graphics Repository (but we extracted it from the jar).
        openButton = new JButton("Open a File...");
        openButton.addActionListener(this);


        //Create the save button.  We use the image from the JLF
        //Graphics Repository (but we extracted it from the jar).
        saveButton = new JButton("Save a File...");
        saveButton.setEnabled(false);
        saveButton.addActionListener(this);
        
        createModel=new JButton("Create Model");
        createModel.setEnabled(false);
        createModel.addActionListener(this);
        
        evalButton= new JButton("Identify");
        evalButton.setEnabled(false);
        evalButton.addActionListener(this);

        //For layout purposes, put the buttons in a separate panel
        JPanel buttonPanel = new JPanel(); //use FlowLayout
        buttonPanel.add(openButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(createModel);
        buttonPanel.add(evalButton);

        //Add the buttons and the log to this panel.
        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e){

        //Handle open button action.
        if (e.getSource() == openButton) {
        	fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        	filter=new javax.swing.filechooser.FileFilter() {
				
				@Override
				public String getDescription() {
					return ".wav";
				}
				
				@Override
				public boolean accept(File f) {
					 return f.isDirectory() || f.getName().toLowerCase().endsWith(".wav");
				}
			};
			fc.setMultiSelectionEnabled(true);
			fc.setAcceptAllFileFilterUsed(false);
        	fc.addChoosableFileFilter(filter);
            int returnVal = fc.showOpenDialog(Window.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
            	file=null;
               file = fc.getSelectedFiles();
               fc.cancelSelection();
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            
            log.setCaretPosition(log.getDocument().getLength());
            
            try {
				mfcc.executeFile(file);
				log.append("mfcc create"+ newline);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
            saveButton.setEnabled(true);

        } else if (e.getSource() == saveButton) {
        	fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        	fc.removeChoosableFileFilter(filter);
            int returnVal = fc.showSaveDialog(Window.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
            	File f = new File(fc.getSelectedFile().getAbsolutePath());
                FileOutputStream fos;
				try {
					fos = new FileOutputStream(f);
					PrintStream ps=new PrintStream(fos);
	                mfcc.createFile(ps);
	                ps.close();
	                fos.close();
	                log.append("File saved"+newline);
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
            
            } else {
                log.append("Save command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());
            createModel.setEnabled(true);
        }
        else if(e.getSource()==createModel){
        	fc.showOpenDialog(Window.this);

				try {
					ClusteringDemo.findCluster(fc.getSelectedFile().getAbsolutePath());
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
//				System.exit(0);
			
			evalButton.setEnabled(true);
			log.append("Models created"+newline);
        }
        else if(e.getSource()==evalButton){
        	try {
				ClusteringDemo.evaluete();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
        }
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Generazione MFCC");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add content to the window.
        frame.add(new Window());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE); 
                createAndShowGUI();
            }
        });
    }
}